<template>
  <Layout>
    <div class="member-settings-container">
      <div class="tabs-header">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="多等级会员模式" name="regular"></el-tab-pane>
          <el-tab-pane label="超级会员模式" name="super"></el-tab-pane>
        </el-tabs>
        <el-button type="primary" @click="handleAddLevel">新增等级</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="memberLevels"
        style="width: 100%"
        border
      >
        <el-table-column prop="level" label="会员等级" width="120" />
        <el-table-column prop="name" label="等级名称" width="150" />
        <el-table-column prop="condition" label="获得条件" />
        <el-table-column prop="benefits" label="会员权益" />
        <el-table-column prop="gifts" label="升级礼包" />
        <el-table-column prop="memberCount" label="会员个数" width="120" />
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="danger" link @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 会员营销 -->
      <div class="marketing-section">
        <div class="section-header">
          <h3>
            会员营销
            <span class="subtitle">精细化运营私域会员，提升会员粘性</span>
          </h3>
        </div>

        <div class="marketing-container">
          <div class="marketing-item">
            <div class="marketing-title">会员专享参与活动</div>
            <div class="marketing-desc">
              会员用户可定期在会员中心领取，持续提升会员黏度
            </div>
            <el-button type="primary" plain>新建活动 ></el-button>
          </div>

          <div class="marketing-item">
            <div class="marketing-title">生日营销</div>
            <div class="marketing-desc">
              会员生日当月可领取生日礼包，提升会员参与度
            </div>
            <el-button type="primary" plain>新建活动 ></el-button>
          </div>

          <div class="marketing-item">
            <div class="marketing-title">积分商城</div>
            <div class="marketing-desc">
              会员用户可定期在会员中心兑换，持续提升会员黏度
            </div>
            <el-button type="primary" plain
              >新建活动 > <span class="pending">(敬请期待)</span></el-button
            >
          </div>
        </div>
      </div>

      <!-- 会员等级编辑对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogType === 'add' ? '新增会员等级' : '编辑会员等级'"
        width="50%"
      >
        <el-form :model="levelForm" label-width="100px">
          <el-form-item label="等级名称">
            <el-input v-model="levelForm.name" placeholder="请输入等级名称" />
          </el-form-item>
          <el-form-item label="等级标识">
            <el-input v-model="levelForm.level" placeholder="例如：VIP1" />
          </el-form-item>
          <el-form-item label="获得条件">
            <el-input
              v-model="levelForm.condition"
              placeholder="例如：消费满500元"
            />
          </el-form-item>
          <el-form-item label="会员权益">
            <el-input
              v-model="levelForm.benefits"
              placeholder="例如：20元优惠券"
            />
          </el-form-item>
          <el-form-item label="升级礼包">
            <el-input
              v-model="levelForm.gifts"
              placeholder="例如：68元抵用金礼包"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="handleSaveLevel"
              :loading="saveLoading"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Layout from "@/components/Layout.vue";
import MemberService from "@/services/MemberService";
import type { MemberLevel } from "@/services/MemberService";

// 当前激活的标签页
const activeTab = ref("regular");

// 数据加载状态
const loading = ref(false);
const saveLoading = ref(false);

// 会员等级数据
const memberLevels = ref<MemberLevel[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref("add");
const levelForm = reactive<MemberLevel>({
  level: "",
  name: "",
  condition: "",
  benefits: "",
  gifts: "",
  memberCount: 0,
});

// 初始化数据
onMounted(async () => {
  // 从后端获取数据
  await fetchMemberLevels();
});

// 获取会员等级列表
const fetchMemberLevels = async () => {
  loading.value = true;
  try {
    memberLevels.value = await MemberService.getMemberLevels();
  } catch (error) {
    console.error("获取会员等级列表失败:", error);
    ElMessage.error("获取会员等级列表失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 新增会员等级
const handleAddLevel = () => {
  dialogType.value = "add";
  levelForm.level = `VIP${memberLevels.value.length + 1}`;
  levelForm.name = "";
  levelForm.condition = "";
  levelForm.benefits = "";
  levelForm.gifts = "";
  levelForm.memberCount = 0;
  dialogVisible.value = true;
};

// 编辑会员等级
const handleEdit = (row: MemberLevel) => {
  dialogType.value = "edit";
  Object.assign(levelForm, row);
  dialogVisible.value = true;
};

// 删除会员等级
const handleDelete = (row: MemberLevel) => {
  if (!row.objectId) {
    ElMessage.warning("无法删除该记录，缺少ID信息");
    return;
  }

  ElMessageBox.confirm(`确定要删除${row.name}会员等级吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      loading.value = true;
      try {
        // 调用API删除
        await MemberService.deleteMemberLevel(row.objectId as string);
        memberLevels.value = memberLevels.value.filter(
          (item: MemberLevel) => item.objectId !== row.objectId
        );
        ElMessage.success("删除成功");
      } catch (error) {
        console.error("删除会员等级失败:", error);
        ElMessage.error("删除失败，请稍后重试");
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 取消删除
    });
};

// 保存会员等级
const handleSaveLevel = async () => {
  if (!levelForm.name) {
    ElMessage.warning("请输入等级名称");
    return;
  }

  if (!levelForm.level) {
    ElMessage.warning("请输入等级标识");
    return;
  }

  saveLoading.value = true;

  try {
    if (dialogType.value === "add") {
      // 新增
      try {
        // 调用API保存
        const newLevel = await MemberService.createMemberLevel({
          level: levelForm.level,
          name: levelForm.name,
          condition: levelForm.condition,
          benefits: levelForm.benefits,
          gifts: levelForm.gifts,
          memberCount: 0,
        });

        memberLevels.value.push(newLevel);
        ElMessage.success("新增成功");
        dialogVisible.value = false;
      } catch (error: any) {
        console.error("新增会员等级失败:", error);
        ElMessage.error(`新增失败: ${error.message || "请稍后重试"}`);
      }
    } else {
      // 编辑
      if (!levelForm.objectId) {
        ElMessage.warning("无法更新该记录，缺少ID信息");
        return;
      }

      try {
        // 调用API更新
        await MemberService.updateMemberLevel(levelForm.objectId, {
          level: levelForm.level,
          name: levelForm.name,
          condition: levelForm.condition,
          benefits: levelForm.benefits,
          gifts: levelForm.gifts,
        });

        const index = memberLevels.value.findIndex(
          (item: MemberLevel) => item.objectId === levelForm.objectId
        );

        if (index !== -1) {
          memberLevels.value[index] = { ...levelForm };
          ElMessage.success("编辑成功");
          dialogVisible.value = false;
        }
      } catch (error: any) {
        console.error("编辑会员等级失败:", error);
        ElMessage.error(`编辑失败: ${error.message || "请稍后重试"}`);
      }
    }
  } catch (error: any) {
    console.error("保存会员等级失败:", error);
    ElMessage.error(`保存失败: ${error.message || "请稍后重试"}`);
  } finally {
    saveLoading.value = false;
  }
};
</script>

<style scoped>
.member-settings-container {
  padding: 20px;
}

.tabs-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header {
  margin: 30px 0 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  margin: 0;
}

.subtitle {
  font-size: 12px;
  color: #999;
  margin-left: 10px;
  font-weight: normal;
}

.marketing-section {
  margin-top: 30px;
}

.marketing-container {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin-top: 20px;
}

.marketing-item {
  width: 30%;
  min-width: 300px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.marketing-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.marketing-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 20px;
  min-height: 40px;
}

.pending {
  color: #999;
  font-size: 12px;
}
</style>
